<template>
  <el-button :icon="Setting" @click="initModalSettings">
    {{ $t('pageUserManagement.accountPolicySettings') }}
  </el-button>
  <el-button type="primary" :icon="Plus" @click="initModalUser">
    {{ $t('pageUserManagement.addUser') }}
  </el-button>
  <div v-if="multipleSelection.length" class="w-full h-8 flex justify-end">
    <el-button @click="batchDelete">
      {{ $t('global.action.delete') }}
    </el-button>
    <el-button @click="batchEnable">
      {{ $t('global.action.enable') }}
    </el-button>
    <el-button @click="batchDisable">
      {{ $t('global.action.disable') }}
    </el-button>
  </div>
  <el-table
    ref="tableRef"
    row-key="id"
    :data="tableItems"
    style="width: 100%"
    @selection-change="handleSelectionChange"
  >
    <el-table-column type="selection" width="55" />
    <el-table-column
      prop="username"
      :label="$t('pageUserManagement.table.username')"
      width="200"
      column-key="id"
    />
    <el-table-column
      prop="privilege"
      :label="$t('pageUserManagement.table.privilege')"
      width="200"
    >
      <template #default="scope">
        <el-tag disable-transitions>{{ scope.row.privilege }}</el-tag>
      </template>
    </el-table-column>
    <el-table-column
      prop="status"
      :label="$t('pageUserManagement.table.status')"
      width="300"
      column-key="date"
    />
    <el-table-column label="Operations">
      <template #default="scope">
        <el-button
          size="small"
          type="danger"
          class="bg-orange-600"
          @click="handlePassword(scope.$index, scope.row)"
          >{{ $t('pageUserManagement.changePassword') }}
        </el-button>
        <el-button
          class="bg-[var(--el-color-primary)]"
          type="primary"
          size="small"
          @click="handleEdit(scope.$index, scope.row)"
          >{{ $t('pageUserManagement.editUser') }}
        </el-button>
        <el-button
          size="small"
          type="danger"
          class="bg-orange-600"
          @click="handleDelete(scope.$index, scope.row)"
          >{{ $t('pageUserManagement.deleteUser') }}
        </el-button>
      </template>
    </el-table-column>
  </el-table>

  <table-roles />
  <modal-change-password
    :user="activeUser"
    :password-requirements="passwordRequirements"
    @ok="changePassword"
    @hidden="activeUser = null"
    ref="ModalChangePasswordDiaglog"
  />
  <modal-settings
    ref="ModalSettingsDiaglog"
    :settings="settings"
    @ok="saveAccountSettings"
  />
  <modal-user
    ref="ModalUserDiaglog"
    :user="activeUser"
    :password-requirements="passwordRequirements"
    @ok="saveUser"
    @hidden="activeUser = null"
  />
</template>

<script setup lang="ts">
import { Setting, Plus } from '@element-plus/icons-vue';
import TableRoles from './TableRoles.vue';
import { useGlobalStore } from '@/store/global';
import { useUserManagementStore } from '@/store/UserSecurity/UserManagement/UserManagementStore';
import { useI18n } from 'vue-i18n';
import ModalChangePassword from './ModalChangePassword.vue';
import ModalSettings from './ModalSettings.vue';
import ModalUser from './ModalUser.vue';

const ModalChangePasswordDiaglog = ref();
const ModalSettingsDiaglog = ref();
const ModalUserDiaglog = ref();

const i18n = useI18n();
const globalStore = useGlobalStore();
const userManagementStore = useUserManagementStore();

await userManagementStore.getUsers();
await userManagementStore.getAccountSettings();
await userManagementStore.getAccountRoles();

const activeUser = ref();
const currentUsername = computed(() => globalStore.username);
const userPrivilege = computed(() => globalStore.userPrivilege);
const allUsers = computed(() => userManagementStore.allUsers);
const tableItems = computed(() => {
  // transform user data to table data
  return allUsers.value.map(
    (user: { UserName: string; RoleId: any; Locked: any; Enabled: any }) => {
      return {
        username: user.UserName,
        privilege: user.RoleId,
        status: user.Locked ? 'Locked' : user.Enabled ? 'Enabled' : 'Disabled',
        actions: [
          {
            value: 'password',
            enabled:
              user.UserName === currentUsername.value ||
              userPrivilege.value === 'Administrator'
                ? true
                : false,
            title: i18n.t('pageUserManagement.changePassword'),
          },
          {
            value: 'edit',
            enabled: true,
            title: i18n.t('pageUserManagement.editUser'),
          },
          {
            value: 'delete',
            enabled: user.UserName === 'root' ? false : true,
            title: i18n.t('pageUserManagement.deleteUser'),
          },
        ],
        ...user,
      };
    },
  );
});

const settings = computed(() => userManagementStore.accountSettings);
const passwordRequirements = computed(
  () => userManagementStore.accountPasswordRequirements,
);

const initModalUser = () => {
  ModalUserDiaglog.value.dialogFormVisible = true;
};
const initModalDelete = (user: { username: any }) => {
  ElMessageBox.confirm(
    i18n.t('pageUserManagement.modal.deleteConfirmMessage', {
      user: user.username,
    }),
    i18n.t('pageUserManagement.deleteUser'),
    {
      confirmButtonText: i18n.t('pageUserManagement.deleteUser'),
      cancelButtonText: i18n.t('global.action.cancel'),
      type: 'warning',
    },
  )
    .then(() => {
      deleteUser(user);
    })
    .catch(() => {});
};
const initModalChangePassword = (user: { username: any }) => {
  activeUser.value = user;
  ModalChangePasswordDiaglog.value.dialogFormVisible = true;
};

const initModalSettings = () => {
  ModalSettingsDiaglog.value.dialogFormVisible = true;
};

const changePassword = (password: string) => {
  userManagementStore
    .changePassword({
      username: activeUser.value.username,
      password,
    })
    .then(() => {
      ElNotification({
        title: 'Success',
        message: i18n.t('pageSessions.table.settingSuccessfully'),
        type: 'success',
      });
    })
    .catch(() => {
      ElNotification({
        title: 'Error',
        message: i18n.t('pageSessions.table.errorSetting'),
        type: 'error',
      });
    });
};

const saveUser = ({
  isNewUser,
  userData,
}: {
  isNewUser: boolean;
  userData: any;
}) => {
  if (isNewUser) {
    userManagementStore
      .createUser(userData)
      .then((success: string) =>
        ElNotification({
          title: 'Success',
          message: success,
          type: 'success',
        }),
      )
      .catch(({ message }: { message: string }) =>
        ElNotification({
          title: 'Error',
          message,
          type: 'error',
        }),
      );
  } else {
    userManagementStore
      .updateUser(userData)
      .then((success: string) =>
        ElNotification({
          title: 'Success',
          message: success,
          type: 'success',
        }),
      )
      .catch(({ message }: { message: string }) =>
        ElNotification({
          title: 'Error',
          message,
          type: 'error',
        }),
      );
  }
};

const deleteUser = ({ username }: { username: string }) => {
  userManagementStore
    .deleteUser(username)
    .then((success: string) =>
      ElNotification({
        title: 'Success',
        message: success,
        type: 'success',
      }),
    )
    .catch(({ message }: { message: string }) =>
      ElNotification({
        title: 'Error',
        message,
        type: 'error',
      }),
    );
};

const handlePassword = (index: number, rowData: any) => {
  initModalChangePassword(rowData);
};

const handleEdit = (index: number, rowData: any) => {
  activeUser.value = rowData;
  initModalUser();
};

const handleDelete = (index: number, rowData: any) => {
  initModalDelete(rowData);
};

const batchDelete = () => {
  ElMessageBox.confirm(
    i18n.t(
      'pageUserManagement.modal.batchDeleteConfirmMessage',
      multipleSelection.value.length,
    ),
    i18n.t('pageUserManagement.deleteUser', multipleSelection.value.length),
    {
      confirmButtonText: i18n.t('global.action.delete'),
      cancelButtonText: i18n.t('global.action.cancel'),
      type: 'warning',
    },
  )
    .then(() => {
      userManagementStore
        .deleteUsers(multipleSelection.value)
        .then((messages: any) => {
          messages.forEach(
            ({ type, message }: { type: string; message: string }) => {
              if (type === 'success')
                ElNotification({
                  title: 'Success',
                  message,
                  type: 'success',
                });
              if (type === 'error')
                ElNotification({
                  title: 'Error',
                  message,
                  type: 'error',
                });
            },
          );
        });
    })
    .catch(() => {});
};

const batchEnable = () => {
  userManagementStore
    .enableUsers(multipleSelection.value)
    .then((messages: any) => {
      messages.forEach(
        ({ type, message }: { type: string; message: string }) => {
          if (type === 'success')
            ElNotification({
              title: 'Success',
              message,
              type: 'success',
            });
          if (type === 'error')
            ElNotification({
              title: 'Error',
              message,
              type: 'error',
            });
        },
      );
    });
};

const batchDisable = () => {
  userManagementStore
    .disableUsers(multipleSelection.value)
    .then((messages: any) => {
      messages.forEach(
        ({ type, message }: { type: string; message: string }) => {
          if (type === 'success')
            ElNotification({
              title: 'Success',
              message,
              type: 'success',
            });
          if (type === 'error')
            ElNotification({
              title: 'Error',
              message,
              type: 'error',
            });
        },
      );
    });
};

const saveAccountSettings = (settings: any) => {
  userManagementStore
    .saveAccountSettings(settings)
    .then((message: string) =>
      ElNotification({
        title: 'Success',
        message,
        type: 'success',
      }),
    )
    .catch(({ message }: { message: string }) =>
      ElNotification({
        title: 'Error',
        message,
        type: 'error',
      }),
    );
};

const multipleSelection = ref([]);

const handleSelectionChange = (val: any) => {
  multipleSelection.value = val;
};
</script>
